package com.handinfo.android.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.resource.ResourceVerifier;

public class UpdateManager
{

	private String curVersion;
	private String newVersion;
	private int curVersionCode;
	private int newVersionCode;
	private String updateInfo;
	private UpdateCallback callback;
	private Context ctx;

	public static int progress=0;
	public static int size=0;
	public static int dqsize=0;
	
	
	
	private Boolean hasNewVersion;
	private Boolean canceled;

	public static String UPDATE_DOWNURL = "http://3gmax.cn/version/xycs_lite.apk"; //"http://192.2.9.191:8080/downloadPro/apps/xycs_lite.apk";//下载包地址

//	public static  String UPDATE_CHECKURL = "http://www.www.baidu.com/test_update/update_version.txt";

	public static  String UPDATE_APKNAME = "xycs_lite.apk";//"xycs_lite.apk";
	//public static final String UPDATE_VERJSON = "ver.txt";
	public static  String UPDATE_SAVENAME = "xycs_lite.apk";//"xycs_lite.apk";
	private static final int UPDATE_CHECKCOMPLETED = 1;
	private static final int UPDATE_DOWNLOADING = 2;
	private static final int UPDATE_DOWNLOAD_ERROR = 3;
	private static final int UPDATE_DOWNLOAD_COMPLETED = 4;
	private static final int UPDATE_DOWNLOAD_CANCELED = 5;


	//private String savefolder = "data/data/com.handinfo.android/files/";
	private String savefolder = "/sdcard/";//目标存放位置
	public boolean zip =false;
	//private String savefolder =  "mnt/sdcard/Download/";
	//public static final String SAVE_FOLDER =Storage. // "/mnt/innerDisk";
	public UpdateManager(Context context, UpdateCallback updateCallback, String url ,String dizhi,boolean zips,String name)
	{
		UPDATE_SAVENAME = name;
		UPDATE_APKNAME = name;
		progress = 0;
		size = 0;
		savefolder = DWGameManager.s_apk_dir + File.separator;
		savefolder = dizhi;
		ctx = context;
		callback = updateCallback;
		UPDATE_DOWNURL = url;
		//savefolder = context.getFilesDir();
		canceled = false;
		zip = zips;
//		int whileKeep = DWGameManager.getInstance().handinfoShared.getInt(IORWFile.sharedxmlResWhileKeep, 0);
//		if (whileKeep == 0) {
//			savefolder = sdCardPath;
//		}
//		else if (whileKeep == 1) {
//			savefolder = dataPath;
//		}
		
		getCurVersion();
	}

	public String getNewVersionName()
	{
		return newVersion;
	}

	public String getUpdateInfo()
	{
		return updateInfo;
	}

	private void getCurVersion()
	{
		try {
			PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(
					ctx.getPackageName(), 0);
			curVersion = pInfo.versionName;
			curVersionCode = pInfo.versionCode;
		}
		catch (NameNotFoundException e) {
			Log.e("update", e.getMessage());
			curVersion = "1.1.1000";
			curVersionCode = 111000;
		}

	}

	public void checkUpdate()
	{
		updateHandler.sendEmptyMessage(UPDATE_CHECKCOMPLETED);
//		hasNewVersion = false;
//		new Thread() {
//			// ***************************************************************
//			/**
//			 * @by wainiwann add
//			 * 
//			 */
//			public void run()
//			{
//				Log.i("", ">>>>>>>>>>>>>>>>>>>>>>>>>>>getServerVerCode() ");
//				try {
//
////					String verjson = NetHelper.httpStringGet(UPDATE_CHECKURL);
////					Log.i("", verjson
////							+ "**************************************************");
////					JSONArray array = new JSONArray(verjson);
//
//					int array = 1;
////					if (array.length() > 0) {
//					if (array > 0) {
//
//						//JSONObject obj = array.getJSONObject(0);
//						try {
//							newVersionCode = 111001;//Integer.parseInt(obj.getString("verCode"));
//							newVersion = "1.1.101";//obj.getString("verName");
//							updateInfo = "";
//							Log.i("newVerCode", newVersionCode
//									+ "");
//							Log.i("newVerName", newVersion
//									+ "");
//							if (newVersionCode > curVersionCode) {
//								hasNewVersion = true;
//							}
//						}
//						catch (Exception e) {
//							newVersionCode = -1;
//							newVersion = "";
//							updateInfo = "";
//
//						}
//					}
//				}
//				catch (Exception e) {
//					Log.e("update", e.getMessage());
//				}
//
//				updateHandler.sendEmptyMessage(UPDATE_CHECKCOMPLETED);
//			
//			};
//			// ***************************************************************
//		}.start();

	}

	public void update()
	{
      DWGameManager.getInstance().destroy();
		Intent intent = new Intent(Intent.ACTION_VIEW);

		intent.setDataAndType(
				Uri.fromFile(new File(savefolder, UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
	
		ctx.startActivity(intent);
		
	}

	// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	public void downloadPackage()
	{
		try {
			URL url = new URL(UPDATE_DOWNURL);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			int length = conn.getContentLength();
			size = length;
			InputStream is = conn.getInputStream();
			
			File apkFolder = new File(savefolder);
			if (!apkFolder.exists()) {
				apkFolder.mkdirs();
			}

			File ApkFile = new File(savefolder, UPDATE_SAVENAME);

			if (ApkFile.exists())
			{
		
				ApkFile.delete();
				
			}else{
			
			}
			
			ApkFile.createNewFile();

			FileOutputStream fos = new FileOutputStream(ApkFile);

			int count = 0;
			byte buf[] = new byte[512];

			do {

				int numread = is.read(buf);
				count += numread;
				dqsize = count;
				progress = (int) (((float) count / length) * 100);
				
				
				//Log.e("progress:", ""+progress);

				updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOADING));
				
			
				
				if (numread <= 0) {
				
					updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_COMPLETED);
					break;
				}
				fos.write(buf, 0, numread);
		
			}
			while (!canceled);
			if (canceled)
			{
				updateHandler.sendEmptyMessage(UPDATE_DOWNLOAD_CANCELED);
			}
	
			fos.close();
			is.close();
		
		}
		catch (MalformedURLException e) {
			e.printStackTrace();

			updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR, e.getMessage()));
		}
		catch (IOException e) {
			e.printStackTrace();

			updateHandler.sendMessage(updateHandler.obtainMessage(UPDATE_DOWNLOAD_ERROR, e.getMessage()));
		}
	}

	public void cancelDownload()
	{
		canceled = true;
	}

	Handler updateHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			
			switch (msg.what) {
				case UPDATE_CHECKCOMPLETED:
		
					//callback.checkUpdateCompleted(hasNewVersion, newVersion);
					new Thread(new Runnable() {
						
						public void run()
						{
							downloadPackage();
						}
					}).start();
					break;
				case UPDATE_DOWNLOADING:

					callback.downloadProgressChanged(progress);
					
					break;
				case UPDATE_DOWNLOAD_ERROR:
					
					//callback.downloadCompleted(false, msg.obj.toString());
					//callback.downloadCanceled();
					break;
				case UPDATE_DOWNLOAD_COMPLETED:
					if(zip){
						((ResourceVerifier)DWGameManager.getInstance().getGameHandler()).httpDownZipstate();
					}else{
						callback.downloadCompleted(true, "");				
					}
					//callback.downloadCanceled();
					break;
				case UPDATE_DOWNLOAD_CANCELED:

//				DWGameManager.getInstance().getGameHandler().setRunning(false);
//				DWGameManager.getInstance().setRunning(false);

					callback.downloadCanceled();
				default:
					break;
			}
		}
	};

	public interface UpdateCallback
	{
		public void checkUpdateCompleted(Boolean hasUpdate,
				CharSequence updateInfo);

		public void downloadProgressChanged(int progress);

		public void downloadCanceled();

		public void downloadCompleted(Boolean sucess, CharSequence errorMsg);
	}

}
